// import backgroundImg from '@/assets/images/background.png';
import backgroundImg from '@/assets/gif/eafb836f6ab3a2df0f2d341056c63dc438ba2bb622f0c1-rQi858.gif';
import Footer from '@/components/Footer';
import { getUserInfoById as queryCurrentUser } from '@/services/groupNumber';
import { authenCert, dummyLogin, jitGWRandom } from '@/services/login';
import { getMenuList as queryMenu } from '@/services/menu';
import { history, useModel } from 'umi';
import { Button, Card, message } from 'antd';
import { JSEncrypt } from 'jsencrypt';
import React, { useState } from 'react';
import { flushSync } from 'react-dom';
import Settings from '../../../../config/defaultSettings';
import attestationUtils from '@/utils/attestationUtils';
import './index.less';
// 签名结果
let signResult;
const Login: React.FC = () => {
  const { initialState, setInitialState } = useModel('@@initialState');
  const [currentUser, setCurrentUser] = useState<any>({});
  const [menuData, setMenuData] = useState<any>([]);
  const fetchUserInfo = async (userId: any) => {
    const userInfo = await queryCurrentUser({
      id: userId,
    });
    if (userInfo.code == '0') {
      const params = {
        roleId: userInfo.data.roleId,
      };
      const menuRes = await queryMenu(params);
      setCurrentUser(userInfo.data);
      setMenuData(menuRes.data);
      return {
        userInfo: userInfo.data,
        menuData: menuRes.data,
      };
    }
  };
  const handleSubmit = async (values: { username: string; password: string }) => {
    try {
      let encrypt = new JSEncrypt();
      encrypt.setPublicKey(Settings.pubilcKey + '');
      let password = encrypt.encrypt(values.password); //password为需要加密的字段
      const params = {
        username: values.username,
        password: password,
      };

      // 登录
      const msg = await dummyLogin(params);
      if (msg.code === '0') {
        // const defaultLoginSuccessMessage = '登录成功！';
        // message.success(defaultLoginSuccessMessage);
        //session 存储
        sessionStorage.setItem('userId', msg.data.id);
        sessionStorage.setItem('userToken', msg.data.token);
        const res = await fetchUserInfo(msg.data.id);
        flushSync(() => {
          setInitialState((s) => ({ ...s, currentUser: res.userInfo, menuData: res.menuData }));
        });
        const urlParams = new URL(window.location.href).searchParams;
        history.push(urlParams.get('redirect') || '/consultCenter/siteSearch');
        return;
      }
    } catch (error) {
      const defaultLoginFailureMessage = '登录失败，请重试！';
      console.log(error);
      message.error(defaultLoginFailureMessage);
    }
  };

  /**
   * jsp认证功能迁移
   */
    //
  const detachSignStr = (initParam: any, authContent: any, signSubject: any) => {
      // 验证认证原文不能为空
      if (authContent == '') {
        alert('认证原文不能为空!');
        return false;
      } else {
        try {
          attestationUtils.JIT_GW_ExtInterface().GetVersion();
        } catch (e) {
          alert('未安装控件，请进行安装控件');
          return false;
        }

        attestationUtils.JIT_GW_ExtInterface().ClearFilter();

        // 初始化vctk控件
        attestationUtils.JIT_GW_ExtInterface().Initialize('', initParam);
        // 控制证书为一个时，不弹出证书选择框
        attestationUtils.JIT_GW_ExtInterface().SetChooseSingleCert(1);

        // 生成签名信息
        const sign_Result = attestationUtils
          .JIT_GW_ExtInterface()
          .P7SignString(authContent, true, true);
        if (attestationUtils.JIT_GW_ExtInterface().GetLastError() != 0) {
          if (
            attestationUtils.JIT_GW_ExtInterface().GetLastError() == 3758096386 ||
            attestationUtils.JIT_GW_ExtInterface().GetLastError() == 2148532334
          ) {
            alert('用户取消操作');
            return;
          } else if (
            attestationUtils.JIT_GW_ExtInterface().GetLastError() == -536870815 ||
            attestationUtils.JIT_GW_ExtInterface().GetLastError() == 3758096481
          ) {
            alert('没有找到有效的证书，如果使用的是KEY，请确认已经插入key');
            return;
          } else {
            alert(attestationUtils.JIT_GW_ExtInterface().GetLastErrorMessage());
            return;
          }
        }
        // 返回签名结果
        return sign_Result;
      }
    };
  // 根据原文和证书产生认证数据包
  const doDataProcess = (original: any) => {
    // 证书版本者主题
    const signSubject = ''; //document.getElementById("rootCADN").value;
    // 验证认证原文是否为空
    if (original == '') {
      alert('认证原文不能为空!');
      return false;
    } else {
      // VCTK初始化参数，数据可从网关系统：认证管理->Key类型管理中导出
      const initParam =
        '<?xml version="1.0" encoding="utf-8"?><authinfo><liblist><lib type="PM" version="1.0" dllname="Q3J5cHRPY3guZGxs"><algid val="SHA1" sm2_hashalg="SM3" /></lib><lib type="CSP" version="1.0" dllname="TWljcm9zb2Z0IEVuaGFuY2VkIENyeXB0b2dyYXBoaWMgUHJvdmlkZXIgdjEuMA=="><algid val="SHA1" sm2_hashalg="SHA1" /></lib><lib type="CSP" version="1.0" dllname="TWljcm9zb2Z0IFN0cm9uZyBDcnlwdG9ncmFwaGljIFByb3ZpZGVy"><algid val="SHA1" sm2_hashalg="SHA1" /></lib><lib type="CSP" version="1.0" dllname="RW50ZXJTYWZlIGVQYXNzMzAwMyBDU1AgdjEuMA=="><algid val="SHA1" sm2_hashalg="SHA1" /></lib><lib type="CSP" version="1.0" dllname="SklUIFVTQiBLZXkgQ1NQIHYxLjA="><algid val="SHA1" sm2_hashalg="SHA1" /></lib><lib type="CSP" version="1.0" dllname="RW50ZXJTYWZlIGVQYXNzMjAwMSBDU1AgdjEuMA=="><algid val="SHA1" sm2_hashalg="SHA1" /></lib><lib type="CSP" version="1.0" dllname="SklUIFVTQiBLZXkzMDAzIENTUCB2MS4w"><algid val="SHA1" sm2_hashalg="SHA1" /></lib><lib type="CSP" version="1.0" dllname="TWljcm9zb2Z0IEJhc2UgQ3J5cHRvZ3JhcGhpYyBQcm92aWRlciB2MS4w"><algid val="SHA1" sm2_hashalg="SHA1" /></lib><lib type="CSP" version="1.0" dllname="RkVJVElBTiBlUGFzc05HIFJTQSBDcnlwdG9ncmFwaGljIFNlcnZpY2UgUHJvdmlkZXI="><algid val="SHA1" sm2_hashalg="SHA1" /></lib><lib type="CSP" version="1.0" dllname="RkVJVElBTiBlUGFzc05HIENTUCBGb3IgSklUM0sgVjEuMA=="><algid val="SHA1" sm2_hashalg="SHA1" /></lib><lib type="SKF" version="1.1" dllname="U2h1dHRsZUNzcDExXzMwMDBHTS5kbGw="><algid val="SHA1" sm2_hashalg="SM3" /></lib><lib type="CSP" version="1.0" dllname="ZVNhZmUgQ3J5cHRvZ3JhcGhpYyBTZXJ2aWNlIFByb3ZpZGVyIHYxLjA="><algid val="SHA1" sm2_hashalg="SHA1" /></lib><lib type="SKF" version="1.0" dllname="R0FLRVlfU0tGLmRsbA=="><algid val="SHA1" sm2_hashalg="SM3" /></lib><lib type="CSP" version="1.0" dllname="R0FTUyBDcnlwdG9ncmFwaGljIFNlcnZpY2UgUHJvdmlkZXIgdjEuMA=="><algid val="SHA1" sm2_hashalg="SHA1" /></lib><lib type="SKF" version="1.0" dllname="L29wdC9HQVNTL2xpYlNLRi9saWJTS0ZfR0FfYXBpLnNv"><algid val="SHA1" sm2_hashalg="SM3" /></lib></liblist></authinfo>';
      // 调用网关工具脚本中的detachSignStr方法进行签名，返回签名结果
      // 参数说明：initParam：vctk控件初始化参数，authContent：认证原文，signSubject：证书版本者主题
      signResult = detachSignStr(initParam, original, signSubject);
      if (signResult) {
        // 设置原文及签名结果
        // document.getElementById("original").value = original;
        // document.getElementById("signed_data").value = signResult;
        // 页面提交，请求后台认证
        // document.forms['certAuth'].submit();
        authenCert({
          original: original,
          original_data: original,
          signed_data: signResult,
          authMode: 'cert',
          pinCode: 'false',
          key_pin: '',
        })
          .then(async (result) => {
            if (result.code == '0') {
              sessionStorage.setItem('userId', result.data.id);
              sessionStorage.setItem('userToken', result.data.token);
              const res = await fetchUserInfo(result.data.id);
              flushSync(() => {
                setInitialState((s) => ({
                  ...s,
                  currentUser: res.userInfo,
                  menuData: res.menuData,
                }));
              });
              const urlParams = new URL(window.location.href).searchParams;
              history.push(urlParams.get('redirect') || '/consultCenter/siteSearch');
              return;
            }
          })
          .catch((err) => {
            message.error('认证失败');
          });
      } else {
        message.error('认证失败');
        return false;
      }
    }
  };
  // 认证
  const attestation = () => {
    // 是否开启二维码认证
    let qrCodeAuth = 'false';
    let original = '';
    jitGWRandom({})
      .then((result) => {
        // console.log(result);
        if (result.data.QRCodeAuth == 'false') {
          original = result.data.original;
          doDataProcess(original);
        } else {
          qrCodeAuth = result.data.QRCodeAuth;
        }
      })
      .catch((err) => {
        console.log(err);
      });
  };

  return (
    <div
      style={{
        display: 'flex',
        flexDirection: 'column',
        height: '100vh',
        overflow: 'auto',
        backgroundImage: 'url(' + `${backgroundImg}` + ')',
        backgroundSize: '100% 100%',
      }}
    >
      <div
        className={'loginBox'}
        style={{
          flex: '1',
          padding: '32px 0',
          color: '#103289',
        }}
      >
        <div className="ant-pro-form-login-top">
          <div className="ant-pro-form-login-header">
            <span className="ant-pro-form-login-logo">
              <img
                data-inspector-line="111"
                data-inspector-column="16"
                data-inspector-relative-path="src\pages\User\Login\index.tsx"
                alt="logo"
                src="/logo_police.png"
              />
            </span>
            <span className="ant-pro-form-login-title">江苏省公安厅特勤局官网后台管理系统</span>
          </div>
        </div>

        <div>
          <Card
            style={{
              width: 300,
              margin: '50px auto',
              backgroundColor: 'aliceblue',
              borderRadius: 10,
              textAlign: 'center',
            }}
          >
            <div style={{ fontSize: 15, color: '#000' }}>请插入数字证书</div>
            <Button style={{ fontSize: 15, marginTop: 10 }} onClick={() => attestation()}>
              认证
            </Button>
          </Card>
        </div>
      </div>
      <Footer />
    </div>
  );
};
export default Login;
